#!/usr/bin/env bash

if [ $EMBOX_GCC_ENV ] && [ -f $EMBOX_GCC_ENV ]; then
	. $EMBOX_GCC_ENV
else
	echo "No EMBOX_GCC_ENV is set" >&2
	exit 1
fi

cppflags="$EMBOX_DEPS_CPPFLAGS_BEFORE $EMBOX_IMPORTED_CPPFLAGS $EMBOX_DEPS_CPPFLAGS_AFTER"

cmd=$(basename $0)
case $cmd in
	*-gcc|*-clang) C_CXX_FLAGS="$cppflags $EMBOX_IMPORTED_CFLAGS";;
	*-g++)         C_CXX_FLAGS="$cppflags $EMBOX_IMPORTED_CXXFLAGS";;
	*)             echo "Unknown flags for $cmd"; exit 1;;
esac

case $EMBOX_GCC_LINK in
	full)
	       	ARG_LINE="$C_CXX_FLAGS $EMBOX_IMPORTED_LDFLAGS $EMBOX_IMPORTED_LDFLAGS_FULL"
		;;
	*)
	       	ARG_LINE="$C_CXX_FLAGS $EMBOX_IMPORTED_LDFLAGS -Wl,-r"
		;;
esac

case " $@ " in
	*" -c "*) ARG_LINE="$C_CXX_FLAGS";;
	*" -E "*) ARG_LINE=;;
	*" -shared "*) echo -e "\n\nCan't build shared objects\n\n"; exit 1;;
	*" -l"*) $0 $(for i in "$@"; do echo ${i/#-l*/}; done); exit $?;;
	*" -I/usr/"*) $0 $(for i in "$@"; do echo ${i/#-I\/usr\/*/}; done); exit $?;;
esac

PWD_ARG_LINE="$(for i in $ARG_LINE; do echo ${i/$PWD/.}; done)"

if [[ "$cmd" == *clang ]]; then
	clang "$@" -target arm-none-eabi $PWD_ARG_LINE
	exit $?
else
	$EMBOX_CROSS_COMPILE${cmd#arch-embox-} "$@" $PWD_ARG_LINE
	exit $?
fi
